package initoy

import (
	
)

type Section struct {
	conf        *Configuration
	comment  string
	name     string
	keys     map[string]*Key
	keyList  []string
	keysHash map[string]string
}

type Key struct {
	sect *Section
	comment string
	name string
	value string
}

// 根据提供的键值对`@kname, @value`在Section中新建一个Key，并返回其指针
func (s *Section) NewKey(kname, value string) (*Key, error) {
	if len(kname) == 0 {
		return nil, &createEmptyKeyError{
			fun : "NewKey",
		}
	}	
	s.keyList = append(s.keyList, kname)
	s.keys[kname] = &Key{
		sect : s,
		name : kname,
		value : value,
	}
	s.keysHash[kname] = value
	return s.keys[kname], nil	
}

// 根据键名`@name`获取Section中对应的Key指针
func (s *Section)GetKey(name string) (*Key, error){
	key := s.keys[name]
	if key == nil {
		return nil, &keyNotExistError{
			sect : s.name, 
			required : name,
		}
	}
	return key, nil
}

// 根据键名`@name`获取Section中对应的Key指针。
// 当Key不存在时，新建一个值为空的Key并返回
func (s *Section) Key(name string) *Key {
	key, err := s.GetKey(name)
	if err != nil {
		// Note: It's OK here because the only possible error is empty section name,
		// but if it's empty, this piece of code won't be executed.
		key, _ = s.NewKey(name, "")
		return key
	}
	return key
}

// 返回当前Section实例的Key列表 
func (s *Section) Keys() []*Key {
	keys := make([]*Key, len(s.keyList))
	for i, name := range s.keyList {
		keys[i] = s.keys[name]
	}
	return keys
}

// 获取Section的注释
func (s *Section) Comment() string {
	return s.comment
}

// 获取Section名称
func (s *Section) Name() string {
	return s.name
}

// 获取Key键名
func (k *Key) Name() string {
	return k.name
}

// 获取Key的值
func (k *Key) Value() string {
	return k.value
}

// 获取Key注释
func (k *Key) Comment() string {
	return k.comment
}